package com.example.kuake.service;


import com.example.kuake.entity.QuarkFile;
import com.example.kuake.entity.QuarkFileListResponse;
import com.example.kuake.entity.QuarkFileExport;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 夸克网盘服务类
 */
@Service
public class QuarkService {

    private final RestTemplate restTemplate;
    
    public QuarkService() {
        this.restTemplate = new RestTemplate();
        // 配置RestTemplate支持gzip解压缩
        this.restTemplate.getMessageConverters().add(0, new org.springframework.http.converter.StringHttpMessageConverter(java.nio.charset.StandardCharsets.UTF_8));
    }
    
    // 夸克网盘真实API地址
    private static final String QUARK_API_BASE = "https://drive-pc.quark.cn/1/clouddrive/file/sort";
    private static final String QUARK_RENAME_API = "https://drive-pc.quark.cn/1/clouddrive/file/rename";

    /**
     * 获取文件列表
     * @param folderId 文件夹ID，默认为"0"表示根目录
     * @param page 页码，从1开始
     * @param pageSize 每页大小
     * @param cookie 夸克网盘Cookie
     * @return 文件列表响应
     */
    public QuarkFileListResponse getFileList(String folderId, Integer page, Integer pageSize, String cookie ,String eagleeyeTraceid) {
        try {
            // 调用夸克网盘真实API
            List<QuarkFile> fileList = callQuarkFileListAPI(folderId, page, pageSize, cookie, eagleeyeTraceid);
            
            // 创建真实API响应结构
            QuarkFileListResponse response = new QuarkFileListResponse();
            response.setStatus(200);
            response.setCode(0);
            response.setMessage("");
            response.setTimestamp(System.currentTimeMillis() / 1000);
            
            // 创建数据对象
            QuarkFileListResponse.Data data = new QuarkFileListResponse.Data();
            data.setList(fileList);
            data.setLastViewList(new ArrayList<>());
            data.setRecentFileList(new ArrayList<>());
            
            // 创建元数据
            QuarkFileListResponse.Metadata metadata = new QuarkFileListResponse.Metadata();
            metadata.setSize(pageSize);
            metadata.setPage(page);
            metadata.setCount(fileList.size());
            metadata.setTotal(fileList.size());
            metadata.setReqId("req_" + System.currentTimeMillis());
            data.setMetadata(metadata);
            
            response.setData(data);
            
            return response;
        } catch (Exception e) {
            return null;
        }
    }



    /**
     * 调用夸克网盘文件列表API
     */
    private List<QuarkFile> callQuarkFileListAPI(String folderId, Integer page, Integer pageSize, String cookie,String eagleeyeTraceid) {
        try {
            HttpHeaders headers = new HttpHeaders();
            // 使用真实的请求头信息
            headers.set("Cookie", cookie);
            headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0");
            headers.set("Accept", "application/json, text/plain, */*");
            headers.set("eagleeye-traceid", eagleeyeTraceid);
            headers.set("content-type", "application/json;charset=UTF-8");
            headers.set("content-encoding", "gzip");


            // 构建GET请求URL，使用你提供的参数格式
            StringBuilder urlBuilder = new StringBuilder(QUARK_API_BASE);
            urlBuilder.append("?pr=ucpro");
            urlBuilder.append("&fr=pc");
            urlBuilder.append("&uc_param_str=");
            urlBuilder.append("&pdir_fid=").append(folderId);
            urlBuilder.append("&_page=").append(page);
            urlBuilder.append("&_size=").append(pageSize);
            urlBuilder.append("&_fetch_total=1");
            urlBuilder.append("&_fetch_sub_dirs=0");
            urlBuilder.append("&_sort=file_type:asc,updated_at:desc");
            HttpEntity<String> requestEntity = new HttpEntity<>(headers);
            
            ResponseEntity<String> response = restTemplate.exchange(
                urlBuilder.toString(), 
                HttpMethod.GET, 
                requestEntity, 
                String.class
            );
            
            // 解析响应数据（这里需要根据实际API响应格式进行解析）
            return parseQuarkFileListResponse(response.getBody());
            
        } catch (Exception e) {
            throw new RuntimeException("调用夸克网盘API失败: " + e.getMessage(), e);
        }
    }



    /**
     * 解析夸克网盘文件列表响应
     */
    private List<QuarkFile> parseQuarkFileListResponse(String responseBody) {
        try {
            com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode rootNode = mapper.readTree(responseBody);
            
            List<QuarkFile> fileList = new ArrayList<>();
            
            // 解析data.list数组
            com.fasterxml.jackson.databind.JsonNode dataNode = rootNode.get("data");
            if (dataNode != null && dataNode.has("list")) {
                com.fasterxml.jackson.databind.JsonNode listNode = dataNode.get("list");
                if (listNode.isArray()) {
                    for (com.fasterxml.jackson.databind.JsonNode fileNode : listNode) {
                        QuarkFile file = new QuarkFile();
                        
                        // 解析文件基本信息
                        file.setFid(fileNode.has("fid") ? fileNode.get("fid").asText() : "");
                        file.setFileName(fileNode.has("file_name") ? fileNode.get("file_name").asText() : "");
                        file.setPdirFid(fileNode.has("pdir_fid") ? fileNode.get("pdir_fid").asText() : "");
                        file.setSize(fileNode.has("size") ? fileNode.get("size").asLong() : 0L);
                        file.setFileType(fileNode.has("file_type") ? fileNode.get("file_type").asInt() : 0);
                        file.setFormatType(fileNode.has("format_type") ? fileNode.get("format_type").asText() : "");
                        file.setDir(fileNode.has("dir") ? fileNode.get("dir").asBoolean() : false);
                        file.setFile(fileNode.has("file") ? fileNode.get("file").asBoolean() : false);
                        file.setIncludeItems(fileNode.has("include_items") ? fileNode.get("include_items").asInt() : 0);
                        file.setCreatedAt(fileNode.has("created_at") ? fileNode.get("created_at").asLong() : 0L);
                        file.setUpdatedAt(fileNode.has("updated_at") ? fileNode.get("updated_at").asLong() : 0L);
                        file.setSource(fileNode.has("source") ? fileNode.get("source").asText() : "");
                        file.setFileSource(fileNode.has("file_source") ? fileNode.get("file_source").asText() : "");
                        
                        // 生成下载链接
                        file.setDownloadUrl("https://pan.quark.cn/download/" + file.getFid());
                        
                        fileList.add(file);
                    }
                }
            }
            
            return fileList;
            
        } catch (Exception e) {
            // 如果解析失败，返回空列表
            return new ArrayList<>();
        }
    }

    /**
     * 重命名文件
     * @param fid 文件ID
     * @param fileName 新文件名
     * @param cookie 夸克网盘Cookie
     * @param eagleeyeTraceid 追踪ID
     * @return 重命名结果
     */
    public String renameFile(String fid, String fileName, String cookie, String eagleeyeTraceid) {
        try {
            // 构建请求体
            String requestBody = String.format("{\"fid\":\"%s\",\"file_name\":\"%s\"}", fid, fileName);
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Cookie", cookie);
            headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0");
            headers.set("Accept", "application/json, text/plain, */*");
            headers.set("eagleeye-traceid", eagleeyeTraceid);
            headers.set("Content-Type", "application/json;charset=UTF-8");
            headers.set("Content-Encoding", "gzip");
            
            // 构建请求URL
            StringBuilder urlBuilder = new StringBuilder(QUARK_RENAME_API);
            urlBuilder.append("?pr=ucpro");
            urlBuilder.append("&fr=pc");
            urlBuilder.append("&uc_param_str=");
            
            // 创建请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
            
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(
                urlBuilder.toString(),
                HttpMethod.POST,
                requestEntity,
                String.class
            );
            
            // 返回响应结果
            return response.getBody();
            
        } catch (Exception e) {
            throw new RuntimeException("重命名文件失败: " + e.getMessage(), e);
        }
    }
    /**
     * 导出所有文件名
     * @param cookie 夸克网盘Cookie
     * @param eagleeyeTraceid 追踪ID
     * @return Excel格式的文件列表字节数组
     */
    public List<QuarkFileExport> exportOneFiles(String folderId,String cookie, String eagleeyeTraceid) {
        try {
            List<QuarkFile> allFiles = new ArrayList<>();
            getAllFilesRecursively(folderId, cookie, eagleeyeTraceid, allFiles);

            // 转换为导出实体
            List<QuarkFileExport> exportData = new ArrayList<>();
            for (QuarkFile file : allFiles) {
                exportData.add(new QuarkFileExport(file));
            }

            return exportData;

        } catch (Exception e) {
            throw new RuntimeException("导出文件列表失败: " + e.getMessage(), e);
        }
    }

    /**
     * 导出所有文件名
     * @param cookie 夸克网盘Cookie
     * @param eagleeyeTraceid 追踪ID
     * @return Excel格式的文件列表字节数组
     */
    public byte[] exportAllFiles(String cookie, String eagleeyeTraceid) {
        try {
            List<QuarkFile> allFiles = new ArrayList<>();
            getAllFilesRecursively("0", cookie, eagleeyeTraceid, allFiles);
            
            // 转换为导出实体
            List<QuarkFileExport> exportData = new ArrayList<>();
            for (QuarkFile file : allFiles) {
                exportData.add(new QuarkFileExport(file));
            }
            
            // 使用EasyExcel生成Excel文件
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            EasyExcel.write(outputStream, QuarkFileExport.class)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                    .sheet("文件列表")
                    .doWrite(exportData);
            
            return outputStream.toByteArray();
            
        } catch (Exception e) {
            throw new RuntimeException("导出文件列表失败: " + e.getMessage(), e);
        }
    }

    /**
     * 递归获取所有文件
     */
    private void getAllFilesRecursively(String folderId, String cookie, String eagleeyeTraceid, List<QuarkFile> allFiles) {
        try {
            List<QuarkFile> files = callQuarkFileListAPI(folderId, 1, 100, cookie, eagleeyeTraceid);
            
            for (QuarkFile file : files) {
                allFiles.add(file);

                System.out.println( "文件id："+file.getFid()+";父级文件id："+file.getFid()+";文件名称："+file.getFileName());
                // 如果是文件夹，递归获取子文件
                if (file.getDir()) {
                    getAllFilesRecursively(file.getFid(), cookie, eagleeyeTraceid, allFiles);
                }
            }
            
        } catch (Exception e) {
            // 忽略单个文件夹的错误，继续处理其他文件夹
            System.err.println("获取文件夹 " + folderId + " 失败: " + e.getMessage());
        }
    }

    /**
     * 批量重命名
     * @param renameData 重命名数据JSON
     * @param cookie 夸克网盘Cookie
     * @param eagleeyeTraceid 追踪ID
     * @return 批量重命名结果
     */
    public String batchRename(String renameData, String cookie, String eagleeyeTraceid) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode renameArray = mapper.readTree(renameData);
            
            List<CompletableFuture<String>> futures = new ArrayList<>();
            ExecutorService executor = Executors.newFixedThreadPool(5); // 限制并发数
            
            for (JsonNode item : renameArray) {
                String fid = item.get("fid").asText();
                String newName = item.get("newName").asText();
                
                CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                    try {
                        return renameFile(fid, newName, cookie, eagleeyeTraceid);
                    } catch (Exception e) {
                        return "重命名失败: " + fid + " -> " + newName + ", 错误: " + e.getMessage();
                    }
                }, executor);
                
                futures.add(future);
            }
            
            // 等待所有任务完成
            CompletableFuture<Void> allFutures = CompletableFuture.allOf(
                futures.toArray(new CompletableFuture[0])
            );
            
            allFutures.get(30, TimeUnit.MINUTES); // 设置超时时间
            
            // 收集结果
            StringBuilder result = new StringBuilder();
            result.append("批量重命名完成！\n");
            result.append("总数量: ").append(futures.size()).append("\n");
            
            int successCount = 0;
            int failCount = 0;
            
            for (CompletableFuture<String> future : futures) {
                String resultStr = future.get();
                if (resultStr.contains("重命名失败")) {
                    failCount++;
                    result.append("失败: ").append(resultStr).append("\n");
                } else {
                    successCount++;
                }
            }
            
            result.append("成功: ").append(successCount).append(" 个\n");
            result.append("失败: ").append(failCount).append(" 个\n");
            
            executor.shutdown();
            return result.toString();
            
        } catch (Exception e) {
            throw new RuntimeException("批量重命名失败: " + e.getMessage(), e);
        }
    }

}